﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MultiThread
{
    public class ThreadOperator
    {
        #region 四个线程同时取50个鸡蛋
        private static List<string> eggs;
        private static object obj = new object();
        public static void CreateMultiThread()
        {
            eggs = new List<string>();
            for (int i = 1; i <= 50; i++)
            {
                string egg = "egg" + i.ToString();
                eggs.Add(egg);
            }

            Thread thread1 = new Thread(ThreadOperator.RunThread1);
            Thread thread2 = new Thread(ThreadOperator.RunThread2);
            Thread thread3 = new Thread(ThreadOperator.RunThread3);
            Thread thread4 = new Thread(ThreadOperator.RunThread4);
            thread1.Name = "Thread1";
            thread2.Name = "Thread2";
            thread3.Name = "Thread3";
            thread4.Name = "Thread4";
            thread1.Start();
            thread2.Start();
            thread3.Start();
            thread4.Start();

        }
        public static void RunThread1()
        {
            GetAnEgg();
            Thread.Sleep(1000);
            RunThread1();

        }
        public static void RunThread2()
        {
            GetAnEgg();
            Thread.Sleep(2000);
            RunThread2();
        }
        public static void RunThread3()
        {
            GetAnEgg();
            Thread.Sleep(3000);
            RunThread3();
        }
        public static void RunThread4()
        {
            GetAnEgg();
            Thread.Sleep(4000);
            RunThread4();
        }
        public static void GetAnEgg()
        {
            lock (obj)
            {
                if (eggs.Count == 0)
                {

                    return ;
                }
                string egg = eggs[0];
                Console.WriteLine(Thread .CurrentThread .Name + "=====" + egg + "==============" + DateTime.Now.ToString("mm--ss"));
                eggs.Remove(egg);
                
             
            }
        }
        #endregion
    }
}
